interface IRongyunViewModel extends ng.IScope {
    setconversation: () => any;
    show: () => any;
    hidden: () => any;
    targetId: any;
    targetType: any;
    user: string;
    realName: string;
    
}

class rongyunController {
    logToken;
    realNameA;
    Lid;
    rongTokenObj;
    numToken: number;
    targetNames: string;
    rongAvatar: string;
    RongKey:string;
    
    strClick:number[]=[];

    constructor(
        private $scope: IRongyunViewModel,
        private $rootScope: ng.IRootScopeService,
        private $http: ng.IHttpService,
        private carService: ICarService,
        private userService: IUserService,
        private $state: ng.ui.IStateService,
        private $ngBootbox: BootboxService,
        private $location: ng.ILocationService,
        private $stateParams: angular.ui.IStateParamsService,
        private WebIMWidget: any

        
    ) {
        /**dev */
        this.RongKey = "82hegw5uhqtcx"
        /**正式服 */
        //this.RongKey="e0x9wycfxzk6q"
        // console.log('rongyunController.js is loaded');
        window.localStorage.getItem("logToken").indexOf('token') > 0 ? this.logToken = JSON.parse(window.localStorage.getItem("logToken")) : this.logToken = window.localStorage.getItem("logToken");

        this.realNameA = JSON.parse(window.localStorage.getItem("loginData"));
        this.Lid = JSON.parse(window.localStorage.getItem("loginData"));
        // this.rongTokenObj = JSON.parse(this.logToken.rongToken);
        this.numToken = 0;
        //console.log(this.logToken.token)
        // this.logToken = "RHUmfzTB09noWoJ9f52mXFRzxVi4xwwEXPtIQQK34ldzmJDqezkHZ2lJjReBNzXvtMhdtEZJnuI8iTkZpuYNcUkgIe8sC0NX";
        this.logToken.token ? this.initRong(this.RongKey, this.logToken.token) : this.initRong(this.RongKey, this.logToken);

        //console.log(this.WebIMWidget)

        /**
         * e0x9wycfxzk6q
         * 
         * 82hegw5uhqtcx
         */
    };


    initRong(key, token): void {

        var self = this;
        this.$scope.setconversation = setconversation;
        this.$scope.show = show;
        this.$scope.hidden = hidden;
        //初始化
        this.WebIMWidget.init({
            appkey: key,
            token: token,
            displayConversationList: true,
            style: {
                left: 3,
                bottom: 3,
                width: 430
            },
            onSuccess: (id) => {
                this.$scope.user = this.realNameA.realName;
                // document.title = '用户：' + id;
                console.log('连接成功：' + this.realNameA.realName);
            },
            onError: (error) => {
                this.numToken++;
                console.log('连接失败：' + error.info);
                
                if (this.numToken > 2) {
                    return;
                } else {
                    this.userService.getRongToken().then((res) => {
                        //console.log(res);
                        // this.isJSON
                        if ( res.data.extData != null) {
                            if( this.isJSON(res.data.extData) && JSON.parse(res.data.extData).token!=null){
                                 let resToken = JSON.parse(res.data.extData).token;
                                  this.initRong(this.RongKey, resToken);
                            }else{
                                let resToken = res.data.extData;
                                 this.initRong(this.RongKey, resToken);
                            }


                        }

                    })
                }
            },
            cb: (rongyun_data) => {
                // console.log('cb',rongyun_data)
                const info = JSON.parse(rongyun_data.content);
                console.log(info)
                if (info && info.MsgType == '0') {
                    let msgType = Number(info.TagType);

                    if (msgType <= 4 ) {  // 询价消息
                        let scopeName = 'refInquiry' + info.TagType;
                        this.$rootScope[scopeName] =  info.Content 

                        if (!this.$scope.$$phase) {
                            this.$scope.$apply(() => { this.$rootScope[scopeName] });
                        }
                        this.$rootScope.$broadcast('WildDog:Inquiry'+msgType,info.Content )
                        
                        window.localStorage.setItem(scopeName, JSON.stringify(this.$rootScope[scopeName]))


                    } else { // 发货消息
                        let scopeName = 'refOrder' + info.TagType;
                        this.$rootScope[scopeName] =  info.Content 
                        if (!this.$scope.$$phase) {
                            this.$scope.$apply(() => { this.$rootScope[scopeName] });
                        }
                        this.$rootScope.$broadcast('WildDog:Order'+msgType,info.Content)
                        window.localStorage.setItem(scopeName, JSON.stringify(this.$rootScope[scopeName]))
                    }




                }

                if (info && info.MsgType == '1') {  // 订单消息
                    this.$rootScope.$broadcast('toaster', info)
                }

                if (info && info.MsgType == '2') {  // 报表导出
                    this.$rootScope.$broadcast('export', info);
                }



            }
        });
        /**设置用户信息 */
        this.WebIMWidget.setUserInfoProvider((targetId, obj) => {
            //console.log(targetId);
            targetId = targetId.replace('_web', '')
            if (targetId != this.Lid.id) {
                this.carService.getDetail(targetId).then((res) => {
                    //console.log(res)
                    this.targetNames = res.data.driver;
                    this.rongAvatar = res.data.certificateImageKey;
                    obj.onSuccess({
                        name: "司机：" + this.targetNames,
                        portraitUri: this.rongAvatar
                    });
                })

            } else {
                obj.onSuccess({
                    name: "调度：" + this.realNameA.realName
                });
            }
        });

        this.WebIMWidget.setGroupInfoProvider((targetId, obj) => {
            obj.onSuccess({
                name: '群组：' + targetId
            });
        })
        /**设置当前会话 */
        var setconversation = () => {
            if (!!this.$scope.targetId) {
                /**单聊,其他会话选择相应的消息类型即可 */
                // this.WebIMWidget.EnumConversationType.PRIVATE
                this.WebIMWidget.setConversation(Number(this.$scope.targetType), this.$scope.targetId, "用户：" + this.targetNames);
                this.WebIMWidget.show();

            }
        }


        var show = () => {
            this.WebIMWidget.show();
        };

        var hidden = () => {
            this.WebIMWidget.hidden();
        };

        this.WebIMWidget.hidden();


    };

    isJSON(str) {
        if (typeof str == 'string') {
            try {
                var obj = JSON.parse(str);
                if (typeof obj == 'object' && obj) {
                    return obj;
                } else {
                    return false;
                }

            } catch (e) {
                console.log('error：' + str + '!!!' + e);
                return false;
            }
        }
        // console.log('It is not a string!')
        return false
    }

}

angular.module('tms').controller('rongyunController', ['$scope', '$rootScope', '$http', 'carService', 'userService', '$state', '$ngBootbox', '$location', '$stateParams', 'WebIMWidget', rongyunController])